clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"

*** 1. Remove files created before
cd "${code}/tba_elig"
local flist1: dir "${Estimates}" files "embs-lps-exogvars*.gph"
local flist2: dir "${Estimates}" files "embs-lps-exogvars*.ster"
foreach f in `flist1' `flist2' {
	cap erase "${Estimates}/`f'"
}
local flist: dir "${log}" files "*"
foreach f of local flist {
	cap erase "${log}/`f'"
}


*** 2. Run regressions
local cmd "sbatch -export=HOME,PATH,SHELL -a 1-4 embs-lps-exogvars.sh" 
di "`cmd'"

local JobIdFile "${log}/job-id.csv"  
log using `JobIdFile', name("jobid") text replace
shell `cmd'
log close _all

do _sbatch-job "`JobIdFile'"


*** 3. combine figures
local pp_list ""
foreach n of numlist 1/4 {
	local pp_list "`pp_list' ${Estimates}/embs-lps-exogvars-`n'.gph"
}

graph combine `pp_list'  
graph export "${figure}/embs-lps-exogvars.pdf", replace


*** 4. Tables

clear
set obs 1
gen PaboveC = 1
gen PaboveC1 = 1
gen Cutoff = 1
gen notba = 1
gen ltvprev_diff = 1
gen HiP = 1


run _esttab-latex-options.do



eststo clear
local mtitle 
foreach n of numlist 1/4 {
	est use "${Estimates}/embs-lps-exogvars-`n'"
	eststo
	
	local DepVar = e(depvar)
	cap gen `DepVar' = 1
	qui do "${code}/_labels"
	
	local depvar_label: variable label `DepVar'
	local mtitle "`mtitle' `"`depvar_label'"'"
	
	estadd local Zip "Y"
	estadd local Lender "Y"
	estadd local Month "Y"
	estadd local control "Y"
}
	
esttab using "${table}/embs-lps-exogvars.tex", replace keep(HiP 1.HiP#c.PaboveC1) coeflabels(1.HiP#c.PaboveC1 "$ z_i\times 1[z_i>0]$") ///
 ${opts_esttab}  b(%9.3fc) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) ///
 stats(Zip Lender Month control N r2_a, fmt(%1s %1s %1s %1s %9.0fc %3.2f) ///
 labels("Zipcode FE" "Lender FE" "Month FE" "Other Controls" "\midrule N. Obs." "Adj. $ R^2$")) ///
 mtitle(`mtitle')

